# -*- coding: utf-8 -*-
import json
import urllib.parse
import urllib.request
from datetime import datetime

from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render

# 开发框架中通过中间件默认是需要登录态的，如有不需要登录的，可添加装饰器login_exempt
# 装饰器引入 from blueapps.account.decorators import login_exempt
from blueapps.account.decorators import login_exempt
from home_application import bk_views
from home_application.models import Script


def home(request):
    """
    首页
    """
    return render(request, 'home_application/index_home.html')


def dev_guide(request):
    """
    开发指引
    """
    return render(request, 'home_application/dev_guide.html')


def contact(request):
    """
    联系页
    """
    return render(request, 'home_application/contact.html')


def get_user(request):
    result = {'result': True, 'user_name': request.user.username}
    return JsonResponse(result)


def search_business(request):
    data = bk_views.search_business()
    result = {'result': True, 'info': data}
    return JsonResponse(result)


def get_job_list(request):
    body = request.GET.dict()
    bk_biz_id = body.get('bk_biz_id')
    data = bk_views.get_job_list(bk_biz_id)
    result = {'result': True, 'info': data}
    return JsonResponse(result)


def get_job_detail(request):
    body = request.GET.dict()
    bk_biz_id = body.get('bk_biz_id')
    bk_job_id = body.get('bk_job_id')
    data = bk_views.get_job_detail(bk_biz_id, bk_job_id)
    result = {'result': True, 'info': data}
    return JsonResponse(result)


def get_all_scripts(request):
    scripts = Script.objects.values().all()
    result = {'result': True, 'info': list(scripts)}
    return JsonResponse(result)


def get_script(request):
    body = request.GET.dict()
    script_id = body.get('script_id')
    script = Script.objects.get(pk=script_id)
    scipt_dict = script.__dict__
    scipt_dict.pop("_state", None)
    result = {'result': True, 'info': scipt_dict}
    return JsonResponse(result)


@login_exempt
def test(request):
    c_url, client_id, client_secret, code, oauth_login_url, uri = get_url(request)
    try:
        user_auth = request.COOKIES.get('user', '')
        if user_auth:
            result = {'result': True, 'user_auth': user_auth}
            return JsonResponse(result)
        # 未携带code,回到教委登录
        if not code:
            return HttpResponseRedirect(oauth_login_url)
        # 拿到code后，获取token
        access_token, access_type, expires_in = get_access_token(client_id, client_secret, code, uri)
        # token获取失效回到教委登录
        if not access_type:
            return HttpResponseRedirect(oauth_login_url)
        else:
            # 获得token后，获取用户信息
            user_info_content, user_info_type = get_user_info(access_token, uri)
            # token失效,回到教委登录
            if not user_info_type:
                return HttpResponseRedirect(oauth_login_url)
            else:
                # 保存用户信息
                user = user_info_content.get('user')
                all_info = {
                    'code': code,
                    'access': {
                        'access_token': access_token,
                        'expires_in': expires_in
                    },
                    'c_url': c_url,
                    'user': user,
                    'time': str(datetime.now())
                }
                script = Script()
                script.content = json.dumps(all_info)
                script.save()
        # 回调url,跳转成功页面
        response = HttpResponseRedirect(c_url)
        # 返回时携带cookie
        response.set_cookie(key='user', value=user.get('UID'), max_age=None, expires=None,
                            path='/',
                            domain='shec.edu.cn',
                            secure=None, httponly=False)
        return response
    except Exception as e:
        script = Script()
        script.content = json.dumps(e.args)
        script.save()
        return HttpResponseRedirect(c_url)


def get_url(request):
    # 获取用户实际请求的URL
    c_url = request.GET.get('state', '')
    # 常量，可放settings
    uri = 'https://oauth.cloud.sh.edu.cn'
    redirect_uri = 'https://ecpaas.shec.edu.cn/t/bk-demo/api/test'
    client_id = 'd368c3bc170b3b07'
    client_secret = 'fc90f147876303c26f3962c74f7bfc05'
    # 回调code
    code = request.GET.get('code', '')
    # 跳转到教委登录的URL
    oauth_login_url = '%s?%s' % (
        uri,
        urllib.parse.urlencode({
            'client_id': client_id,
            'redirect_uri': redirect_uri,
            'state': c_url
        })
    )
    return c_url, client_id, client_secret, code, oauth_login_url, uri


def get_user_info(access_token, uri):
    user_info_uri = '%s/%s' % (uri, 'oauth/GetUserInfo')
    user_info_oauth_url = '%s?%s' % (
        user_info_uri,
        urllib.parse.urlencode({
            'access_token': access_token
        })
    )
    user_info_res = urllib.request.urlopen(user_info_oauth_url)
    user_info_content = json.loads(user_info_res.read().decode("utf-8"))
    user_info_type = user_info_content.get('type')
    return user_info_content, user_info_type


def get_access_token(client_id, client_secret, code, uri):
    access_token_uri = '%s/%s' % (uri, 'oauth/GetAccessToken')
    access_token_oauth_url = '%s?%s' % (
        access_token_uri,
        urllib.parse.urlencode({
            'client_id': client_id,
            'code': code,
            'client_secret': client_secret
        })
    )
    access_token_res = urllib.request.urlopen(access_token_oauth_url)
    access_token_content = json.loads(access_token_res.read().decode("utf-8"))
    access_token = access_token_content.get('access_token')
    expires_in = access_token_content.get('expires_in')
    access_type = int(access_token_content.get('type'))
    return access_token, access_type, expires_in
